package com.mango.community.controller.interceptor;

import com.mango.community.entity.LoginTicket;
import com.mango.community.entity.User;
import com.mango.community.service.UserService;
import com.mango.community.util.CookieUtil;
import com.mango.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/7/25 16:10
 * 登录的拦截器
 */
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     * 在执行controller之前执行 拦截需要拦截的信息的地方
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从request中获取cookie,在从cookie中获取凭证
        String ticket = CookieUtil.getValue(request,"ticket");
        if(ticket !=null){
            //查询凭证
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            //判断凭证是否有效（凭证状态失效或者凭证时间超时）
            if(loginTicket !=null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())){
                //根据获取到的凭证对象中放入userId得到user
                User user = userService.findUserById(loginTicket.getUserId());
                //在本次请求中持有用户，这次存储只在本次请求中有效
                hostHolder.setUser(user);
            }
        }

        //一般都是返回true程序才会向下执行 ，返回false 是在特定情况下不让程序继续执行
        return true;
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     * 在调用controller之后调用，在调用模板引擎之前调用，并且有ModelAndView对象，可以将模板要使用的数据放进去，供模板使用
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //获取当前线程持有的user对象
        User user = hostHolder.getUser();
        //判断空值
        if(user != null && modelAndView != null){
            //不为空的时候将user对象放到modelAndView中
            modelAndView.addObject("loginUser",user);
        }
    }

    /**   在调用模板之后执行，在这里将线程对象中的数据清理
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理的线程对象中的数据（他是存在内存中的）
        hostHolder.clear();
    }

}
